package primeiro.jogoandroid;

import android.content.Context;
import android.content.res.Resources.Theme;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;

public class GameView extends View implements Runnable{

	private static final int INTERVAL = 10;
	private boolean running = true;
	private int y;
	private Paint paint;
	private Inimigo[] inimigos;
	
	public GameView(Context context) {
		super(context);
		
		paint = new Paint();
		Thread minhaThread = new Thread(this);
		minhaThread.setPriority(Thread.MIN_PRIORITY);
		minhaThread.start();
	}

	@Override
	public void run() {
		while (running) {
			try {
				Thread.sleep(INTERVAL);
			} catch (Exception e) {
				Log.e("Erro", e.getMessage());
			}
			update();
		}
	}
	
	private void update(){
		if(inimigos==null){
			return;
		}
		
// era so pra descer o quadradinho do primeiro exemplo		
//		if (y < getHeight()) {
//			y+=5;
//		}else {
//			y = 0;
//		}
		
		for (int i = 0; i < inimigos.length; i++) {
			inimigos[i].mexe(getWidth(), getHeight());
		}
		
		//dispate o metodo draw(p/desenhar);
		postInvalidate(); 
	}
	
	//vai desenhar a tela
	public void draw(Canvas canvas){
		super.draw(canvas);
		if(inimigos==null){
			iniciaJogo();
		}
		
		canvas.drawColor(Color.BLACK);
		for (int i = 0; i < inimigos.length; i++) {
			inimigos[i].draw(canvas, paint);
		}
	}
	
	public void release(){
		running = false;
	}
	
	public void iniciaJogo(){
		BotaoEsquerda botaoE = new BotaoEsquerda(10, 30);
		inimigos = new Inimigo[getHeight()/50];
		for (int i = 0; i < inimigos.length; i++) {
			int y = i * -50;
			int x = (int) (Math.random()*getWidth()-25);
			inimigos[i] = new Inimigo(x, y);
		}
	}
	
	public boolean onTouchEvent(MotionEvent event){
		if(event.getAction() == MotionEvent.ACTION_DOWN){
			int x = (int) event.getX();
			int y = (int) event.getY();
			for (int i = 0; i < inimigos.length; i++) {
				if(inimigos[i].colide(x, y)){
					inimigos[i].setX(-70);
				}
			}
		}
		return super.onTouchEvent(event);
	}
}
